'use client'
import { useEffect, useState } from "react";
import { deleteComment, getUserComments } from "@/app/service/commentService";
import {
  Button,
  Chip,
  Divider,
  Spinner,
  Tooltip,
  Pagination,
  Avatar,
} from "@nextui-org/react";
import { useRouter } from "next/navigation";
import { BiArrowBack } from "react-icons/bi";
import { HiOutlineTrash } from "react-icons/hi";
import { FiMessageSquare } from "react-icons/fi";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import 'dayjs/locale/zh-cn';

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

export default function CommentsPage() {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(true);
  const [comments, setComments] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [selectedComment, setSelectedComment] = useState<any | null>(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  // 分页设置
  const pageSize = 10;

  // 初次加载和分页变化时获取数据
  useEffect(() => {
    fetchComments();
  }, [page]);

  // 获取评论列表
  const fetchComments = async () => {
    setIsLoading(true);
    try {
      const response = await getUserComments(page, pageSize);
      if (response && response.code === 200) {
        if (response.data && response.data.records) {
          setComments(response.data.records);
          setTotal(response.data.total || 0);
        } else {
          setComments([]);
          setTotal(0);
        }
      } else {
        setComments([]);
        setTotal(0);
      }
    } catch (error) {
      console.error("Failed to fetch comments:", error);
      setComments([]);
      setTotal(0);
    } finally {
      setIsLoading(false);
    }
  };

  // 处理删除评论
  const handleDeleteComment = async (commentId: number) => {
    try {
      await deleteComment(commentId);
      fetchComments();
      setShowDeleteConfirm(false);
      setSelectedComment(null);
    } catch (error) {
      console.error("Failed to delete comment:", error);
    }
  };

  // 格式化日期
  const formatDate = (date: string) => {
    if (!date) return "";
    return dayjs(date).fromNow();
  };

  // 查看对应笔记
  const viewNote = (noteId: number) => {
    router.push(`/note/${noteId}`);
  };

  // 返回上一页
  const handleGoBack = () => {
    router.back();
  };

  return (
    <div className="bg-background min-h-screen">
      {/* 标题栏 */}
      <div className="py-4 px-4 bg-background border-b border-divider">
        <div className="flex items-center max-w-5xl mx-auto">
          <Button
            isIconOnly
            variant="light"
            onPress={handleGoBack}
            className="mr-2"
          >
            <BiArrowBack size={20} />
          </Button>
          <div className="flex items-center">
            <FiMessageSquare className="text-primary mr-2" size={20} />
            <h1 className="text-xl font-semibold">我的评论</h1>
          </div>
        </div>
      </div>

      {/* 内容区域 */}
      <div className="max-w-5xl mx-auto px-4 py-6">
        {isLoading ? (
          <div className="flex justify-center items-center py-20">
            <Spinner label="加载中..." color="primary" />
          </div>
        ) : comments.length === 0 ? (
          <div className="text-center py-20">
            <p className="text-gray-500 dark:text-gray-400">暂无评论</p>
          </div>
        ) : (
          <div className="space-y-6">
            {comments.map((comment) => (
              <div 
                key={comment.id} 
                className="border border-divider rounded-lg p-4 bg-content1 transition-all"
              >
                <div className="flex items-start gap-3">
                  <Avatar
                    src={comment.userAvatar}
                    name={comment.userName?.charAt(0) || "U"}
                    size="sm"
                    className="flex-shrink-0"
                  />
                  <div className="flex-grow">
                    <div className="flex justify-between items-start mb-2">
                      <div 
                        className="cursor-pointer hover:text-primary transition-colors"
                        onClick={() => viewNote(comment.noteId)}
                      >
                        <h3 className="font-medium">{comment.noteTitle || `笔记 #${comment.noteId}`}</h3>
                      </div>
                      <Chip size="sm" variant="flat" color="primary">
                        {formatDate(comment.createdAt)}
                      </Chip>
                    </div>
                    
                    <p className="text-foreground-700 py-2">{comment.content}</p>
                    
                    {selectedComment?.id === comment.id && showDeleteConfirm && (
                      <div className="mt-3 p-3 border border-danger-200 rounded-md bg-danger-50 dark:bg-danger-900/20">
                        <p className="text-sm text-danger mb-2">确定要删除此评论吗？</p>
                        <div className="flex justify-end gap-2">
                          <Button 
                            size="sm" 
                            variant="flat" 
                            onPress={() => {
                              setShowDeleteConfirm(false);
                              setSelectedComment(null);
                            }}
                          >
                            取消
                          </Button>
                          <Button 
                            size="sm" 
                            color="danger" 
                            onPress={() => handleDeleteComment(comment.id)}
                          >
                            确认删除
                          </Button>
                        </div>
                      </div>
                    )}
                    
                    <div className="flex justify-end mt-2">
                      <Tooltip content="删除评论" color="danger">
                        <Button
                          isIconOnly
                          size="sm"
                          variant="light"
                          color="danger"
                          onPress={() => {
                            setSelectedComment(comment);
                            setShowDeleteConfirm(true);
                          }}
                        >
                          <HiOutlineTrash size={16} />
                        </Button>
                      </Tooltip>
                    </div>
                  </div>
                </div>
              </div>
            ))}
            
            {/* 分页 */}
            {total > pageSize && (
              <div className="flex justify-center mt-8">
                <Pagination
                  total={Math.ceil(total / pageSize)}
                  initialPage={1}
                  page={page}
                  onChange={setPage}
                  showControls
                />
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
} 